#!/usr/bin/env python

from Tkinter import *
import hashlib

def goodpass(p):
	has_lower = False
	has_upper = False
	has_digit = False
	has_other = False
	for c in p:
		if c.islower():
			has_lower = True
		elif c.isupper():
			has_upper = True
		elif c.isdigit():
			has_digit = True
		else:
			has_other = True
	return has_lower and has_upper and has_digit and has_other

def ascii_trans(s):
	return ''.join([chr(33 + ord(c) % 94) for c in s])

def genpass(user, site, master):
	d = user + '\n' + site + '\n' + master

	while True:
		hash = hashlib.sha512()
		hash.update(d)
		d = hash.digest()

		password = ascii_trans(d)
		if goodpass(password[:8]):
			break

	return password

def main():
	def gen_callback():
		password = genpass(user.get(), site.get(), master.get())

		result['state'] = NORMAL
		result.delete(0, END)
		result.insert(0, password)
		result['state'] = 'readonly'

		shorten['state'] = NORMAL
		shorten.delete(0, END)
		shorten.insert(0, password[:25])
		shorten['state'] = 'readonly'

	def return_callback(e):
		gen_callback()

	root = Tk()
	root.title('epicpass')

	Label(text='user:').pack()
	user = Entry(root, width=100)
	user.focus_set()
	user.pack()

	Label(text='site:').pack()
	site = Entry(root, width=100)
	site.pack()

	Label(text='master:').pack()
	master = Entry(root, width=100)
	master.pack()

	gen = Button(root, text='generate', command=gen_callback, default=ACTIVE)
	gen.pack()

	result = Entry(root, width=100, state='readonly')
	result.pack()

	shorten = Entry(root, width=100, state='readonly')
	shorten.pack()

	root.bind('<Return>', return_callback)
	root.mainloop()

if __name__ == '__main__':
	main()

